package learnScala

object ScalaWordCount {
    def main(args: Array[String]): Unit = {
        val lst = scala.io.Source.fromFile("D:/project/KafkaSparkStreaming/src/main/resources/word.txt").getLines.toList.flatMap(_.split(" +")).groupBy(s=>s).mapValues(_.length)
        lst.foreach(println)
    }

    /*分解

    //读取文件
    scala> val it1 = io.Source.fromFile("e:/1.txt")
    it1: scala.io.BufferedSource = non-empty iterator
        //获取所有行的迭代器
        scala> val it2 = it1.getLines
    it2: Iterator[String] = non-empty iterator
        //将其转为列表
        scala> val lst1 = it2.toList
    lst1: List[String] = List(hello nihao, shi jie, shijie, hello jie, "en en en ", hao hao, hao en)
    //压平，生成字符串类型的列表，而不是数组类型的列表
    scala> val lst2 = lst1.flatMap(_.split(" +"))
    lst2: List[String] = List(hello, nihao, shi, jie, shijie, hello, jie, en, en, en, hao, hao, hao, en)
    复制代码
    //按元素进行分组
    scala> val map1 = lst2.groupBy(s=>s)
    map1: scala.collection.immutable.Map[String,List[String]] =
    　　　　　　Map(shi -> List(shi),
        en -> List(en, en, en, en),
        jie -> List(jie, jie),
        shijie -> List(shijie),
        hao -> List(hao, hao, hao),
        hello -> List(hello, hello),
        nihao -> List(nihao))
    复制代码
    //对 v 进行转换
    scala> val map2 = map1.mapValues(_.length)
    map2: scala.collection.immutable.Map[String,Int] = Map(shi -> 1, en -> 4, jie -> 2, shijie -> 1, hao -> 3, hello -> 2, nihao -> 1)*/
}
